<?php

namespace backend\models;


/**
 * This is the model class for table "ht_role".
 *
 * @property string $id 分类
 * @property string $name 分类名
 * @property string $level 分类名
 * @property int $create_time 创建时间
 * @property int $fid 父id
 * @property int $type 分类类型
 * @property int $status 状态
 */
class Category extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'ht_category';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['name','unique'],
            [['create_time','fid','type','status'], 'integer'],
            [['name'], 'string', 'max' => 20],
            [['level'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '分类名称',
            'type' => '分类类型',
            'create_time' => '创建时间',
        ];
    }

    public function create($data)
    {
        $this->name = $data['name'];
        $this->fid = (int)$data['fid'];
        $this->create_time = time();
        $tran = \Yii::$app->db->beginTransaction();
        if($this->validate()){
            try{
                $this->save();
                $id = \Yii::$app->db->getLastInsertID();
                $this->level = $this->fid==0? '0'.'-'.$id: self::findOne($this->fid)->level.'-'.$id;
                $this->save();
                $tran->commit();
                return $this->arrData(200, '添加成功');
            }catch (\Exception $e){
                $tran->rollBack();
                $error = array_values($this->getFirstErrors())[0];
                return $this->arrData(100, $error);
            }
        }
    }


    /**
     * 判断是否有子集
     * @param $data
     * @return mixed
     */
    public static function isChildren($data){
        if(empty($data)){
            return $data;
        }
        foreach ($data as $key=>$val){
            $model = self::findOne(['fid'=>$val['id']]);
            if(!empty($model)){
                $data[$key]['children']=1;
            }else{
                $data[$key]['children']=0;
            }
        }
        return $data;
    }

    // 获取分类树
    public static function getTree($data,$fid=0){
        if(empty($data)){
            return $data;
        }
        $tree = [];
        foreach ($data as $key=>$val){
            if($val['fid']==$fid){
                $val['children'] = self::getTree($data,$val['id']);
                $tree[] = $val;
            }
        }
        return $tree;
    }

    // 获取所有分类
    public static function categoryTree($category)
    {
        $category = self::addPrefixT($category);
        return $category;
    }

    // 分类添加前缀
    public static function addPrefixT($data){
        if(empty($data)){
            return $data;
        }
        foreach ($data as $key=>$val){
            $prefix = '|--&nbsp;&nbsp;&nbsp;&nbsp;';
            $num = count(explode('-',$val['level']))-2;
            $data[$key]['name'] = str_repeat($prefix,$num).$val['name'];
        }
        return $data;
    }
    // 获取所有分类
    public static function getAllTree()
    {
        $category = self::find()->orderBy(['level'=>SORT_ASC])->asArray()->all();
        $category = self::addPrefixT($category);
        $top_level = ['pid'=>'0','name'=>'--顶级分类--','level'=>0];
        array_unshift($category,$top_level);
        return $category;
    }

}
